import React from 'react';
import { useEditorStore } from '../store/useEditorStore';
import { formatYAML, validateYAML } from '../utils/yaml';
import { 
  FileText, 
  FolderOpen, 
  Save, 
  Download, 
  Wand2, 
  CheckCircle, 
  Trash2, 
  Copy, 
  Upload,
  AlertCircle,
  Check
} from 'lucide-react';
import { toast } from 'sonner';

interface ToolbarProps {
  className?: string;
}

const Toolbar: React.FC<ToolbarProps> = ({ className = '' }) => {
  const {
    content,
    filename,
    isDirty,
    validation,
    newFile,
    setContent,
    saveFile,
    loadFile,
    validateContent
  } = useEditorStore();

  // 新建文件
  const handleNewFile = () => {
    if (isDirty) {
      const confirmed = window.confirm('当前文件有未保存的更改，确定要新建文件吗？');
      if (!confirmed) return;
    }
    newFile();
    toast.success('已新建文件');
  };

  // 打开文件
  const handleOpenFile = async () => {
    if (isDirty) {
      const confirmed = window.confirm('当前文件有未保存的更改，确定要打开新文件吗？');
      if (!confirmed) return;
    }

    try {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.yaml,.yml,.txt';
      input.onchange = async (e) => {
        const file = (e.target as HTMLInputElement).files?.[0];
        if (file) {
          try {
            const content = await file.text();
            loadFile(file.name, content);
            toast.success(`已打开文件: ${file.name}`);
          } catch (error) {
            toast.error('文件读取失败: ' + (error instanceof Error ? error.message : '未知错误'));
          }
        }
      };
      input.click();
    } catch (error) {
      toast.error('打开文件失败');
    }
  };

  // 保存文件
  const handleSaveFile = () => {
    try {
      saveFile();
      toast.success('文件已保存');
    } catch (error) {
      toast.error('保存失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 下载文件
  const handleDownloadFile = () => {
    try {
      const blob = new Blob([content], { type: 'text/yaml;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename || 'untitled.yaml';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      toast.success('文件已下载');
    } catch (error) {
      toast.error('下载失败');
    }
  };

  // 格式化YAML
  const handleFormatYaml = () => {
    try {
      const formatted = formatYAML(content);
      setContent(formatted);
      toast.success('YAML已格式化');
    } catch (error) {
      toast.error('格式化失败: ' + (error instanceof Error ? error.message : '未知错误'));
    }
  };

  // 验证YAML
  const handleValidateYaml = () => {
    try {
      validateContent();
      if (validation.isValid) {
        toast.success('YAML格式正确');
      } else {
        toast.error(`发现 ${validation.errors.length} 个错误`);
      }
    } catch (error) {
      toast.error('验证失败');
    }
  };

  // 清空内容
  const handleClearContent = () => {
    const confirmed = window.confirm('确定要清空所有内容吗？此操作不可撤销。');
    if (confirmed) {
      setContent('');
      toast.success('内容已清空');
    }
  };

  // 复制内容
  const handleCopyContent = async () => {
    try {
      await navigator.clipboard.writeText(content);
      toast.success('内容已复制到剪贴板');
    } catch (error) {
      // 降级方案
      const textArea = document.createElement('textarea');
      textArea.value = content;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      toast.success('内容已复制到剪贴板');
    }
  };

  // 从剪贴板粘贴
  const handlePasteContent = async () => {
    try {
      const text = await navigator.clipboard.readText();
      if (text) {
        if (content && isDirty) {
          const confirmed = window.confirm('当前有内容，确定要替换吗？');
          if (!confirmed) return;
        }
        setContent(text);
        toast.success('内容已从剪贴板粘贴');
      }
    } catch (error) {
      toast.error('粘贴失败，请手动粘贴');
    }
  };

  const toolbarButtons = [
    {
      icon: FileText,
      label: '新建',
      onClick: handleNewFile,
      shortcut: 'Ctrl+N'
    },
    {
      icon: FolderOpen,
      label: '打开',
      onClick: handleOpenFile,
      shortcut: 'Ctrl+O'
    },
    {
      icon: Save,
      label: '保存',
      onClick: handleSaveFile,
      shortcut: 'Ctrl+S',
      disabled: !isDirty
    },
    {
      icon: Download,
      label: '下载',
      onClick: handleDownloadFile,
      shortcut: 'Ctrl+D'
    },
    { type: 'separator' },
    {
      icon: Wand2,
      label: '格式化',
      onClick: handleFormatYaml,
      shortcut: 'Ctrl+Shift+F',
      disabled: !content.trim()
    },
    {
      icon: validation.isValid ? CheckCircle : AlertCircle,
      label: '验证',
      onClick: handleValidateYaml,
      shortcut: 'Ctrl+Shift+V',
      disabled: !content.trim(),
      className: validation.isValid ? 'text-green-600' : validation.errors.length > 0 ? 'text-red-600' : ''
    },
    { type: 'separator' },
    {
      icon: Copy,
      label: '复制',
      onClick: handleCopyContent,
      shortcut: 'Ctrl+Shift+C',
      disabled: !content.trim()
    },
    {
      icon: Upload,
      label: '粘贴',
      onClick: handlePasteContent,
      shortcut: 'Ctrl+Shift+V'
    },
    {
      icon: Trash2,
      label: '清空',
      onClick: handleClearContent,
      shortcut: 'Ctrl+Shift+X',
      disabled: !content.trim(),
      className: 'text-red-600 hover:text-red-700'
    }
  ];

  return (
    <div className={`flex items-center space-x-1 p-2 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 ${className}`}>
      {toolbarButtons.map((button, index) => {
        if (button.type === 'separator') {
          return (
            <div 
              key={`separator-${index}`} 
              className="w-px h-6 bg-gray-300 dark:bg-gray-600 mx-2"
            />
          );
        }

        const Icon = button.icon;
        const isDisabled = button.disabled;

        return (
          <button
            key={button.label}
            onClick={button.onClick}
            disabled={isDisabled}
            title={`${button.label} (${button.shortcut})`}
            className={`
              flex items-center px-3 py-2 text-sm rounded transition-colors
              ${isDisabled 
                ? 'text-gray-400 cursor-not-allowed' 
                : `text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 active:bg-gray-200 dark:active:bg-gray-700 ${button.className || ''}`
              }
            `}
          >
            <Icon className="w-4 h-4 mr-1" />
            <span className="hidden sm:inline">{button.label}</span>
          </button>
        );
      })}

      {/* 文件状态指示器 */}
      <div className="flex-1" />
      <div className="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400">
        {isDirty && (
          <span className="flex items-center text-orange-600 dark:text-orange-400">
            <div className="w-2 h-2 bg-orange-500 rounded-full mr-1" />
            未保存
          </span>
        )}
        {validation.errors.length > 0 && (
          <span className="flex items-center text-red-600 dark:text-red-400">
            <AlertCircle className="w-4 h-4 mr-1" />
            {validation.errors.length} 个错误
          </span>
        )}
        {validation.isValid && content.trim() && (
          <span className="flex items-center text-green-600 dark:text-green-400">
            <Check className="w-4 h-4 mr-1" />
            格式正确
          </span>
        )}
      </div>
    </div>
  );
};

export default Toolbar;